package com.aabte.quartz.demo;

import lombok.extern.log4j.Log4j;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;

import java.util.Date;

import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.DateBuilder.evenMinuteDate;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

@Log4j
public class SimpleCronExample {

    public static void main(String[] args) throws Exception {

        SimpleCronExample simpleExample = new SimpleCronExample();
        simpleExample.run();

    }

    private void run() throws Exception {
        log.info("----- Initializing -----");

        StdSchedulerFactory factory = new StdSchedulerFactory();
        Scheduler scheduler = factory.getScheduler();

        log.info("----- Initialization Complete -----");

        Date runTime = evenMinuteDate(new Date());

        log.info("----- Scheduling Job -----");

        JobDetail jobDetail = newJob(HelloJob.class)
                .withIdentity("job1", "group1")
                .build();

        Trigger trigger = newTrigger()
                .withIdentity("trigger1", "group1")
                .withSchedule(cronSchedule("0/5 * * * * ?"))
                .build();

        scheduler.scheduleJob(jobDetail, trigger);
        log.info(jobDetail.getKey() + " will run at: " + runTime);

        scheduler.start();

        log.info("----- Waiting 60 seconds... -----");

        Thread.sleep(60*1000);

        log.info("----- Shutting Down -----");
        scheduler.shutdown(true);
        log.info("----- Shutting Complete -----");

    }

}
